package com.atguigu.flink08;

import com.atguigu.beans.WaterSensor;
import com.atguigu.func.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/2/27
 * 该案例演示规约状态
 * 需求：计算每种传感器的水位和
 */
public class Flink06_State_ReducingState {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> wsDS = env
                .socketTextStream("hadoop102", 8888)
                .map(new WaterSensorMapFunction());
        
        wsDS
                .keyBy(WaterSensor::getId)
                .process(
                        new KeyedProcessFunction<String, WaterSensor, String>() {
                            //声明状态
                            ReducingState<Integer> vcReduceState;

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                //状态初始化
                                ReducingStateDescriptor<Integer> reducingStateDescriptor
                                        = new ReducingStateDescriptor<Integer>("vcReduceState", new ReduceFunction<Integer>() {
                                    @Override
                                    public Integer reduce(Integer value1, Integer value2) throws Exception {
                                        return value1 + value2;
                                    }
                                }, Integer.class);
                                vcReduceState = getRuntimeContext().getReducingState(reducingStateDescriptor);
                            }

                            @Override
                            public void processElement(WaterSensor ws, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                                    vcReduceState.add(ws.vc);
                                    out.collect("当前传感器"+ ws.id+"，水位和是：" + vcReduceState.get());
                            }
                        }
                ).print();

        env.execute();
    }
}
